
#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>

void Child_Write(int f)
{
    int n=0;
    char buffer[1024]={0};
    while(1)
    {
        snprintf(buffer,sizeof(buffer),"I am child,my pid is:%d,n:%d",getpid(),n++);
        write(f,buffer,strlen(buffer));
        sleep(1);
    }
}


void Parent_Read(int f)
{
    char buffer[1024]={0};
    while(1)
    {
        ssize_t ret=read(f,buffer,sizeof(buffer)-1);
        if(ret>0)
        printf("Chird say:%s\n",buffer);
    }


}




int main()
{
    int fds[2]={0};
    int ret=pipe(fds);
    if(ret<0)
    {
        std::cerr<<"pipe error"<<std::endl;
    }


    // std::cout<<"fds[0]:"<<fds[0]<<std::endl;
    // std::cout<<"fds[1]:"<<fds[1]<<std::endl;
    
    pid_t id=fork();
    if(id==0)
    {
        //子进程
        //子进程关闭读
        close(fds[0]);
        Child_Write(fds[1]);

        close(fds[1]);

    }
    //父进程关闭读
    close(fds[1]);
    Parent_Read(fds[0]);

    waitpid(id,nullptr,0);
    close(fds[0]);



    return 0;
}